// Time Tracker by Eric Nadeau (nado18@gmail.com)
// Copyright (C) 2007 by Eric Nadeau
// Distributed under the terms of the GNU General Public License (see GPL.txt)

package view;

import java.awt.*;
import java.awt.event.*;
import java.util.*;

import javax.swing.*;
import javax.swing.event.*;

/**
 * I extend the standard JTextField to give users feedback on their input
 * from a given regex. Upon error, I will be slightly red. I also provide
 * the +isInputValid():boolean method for convenience.
 * 
 * @author Eric Nadeau (nado18@gmail.com) on Dec 13 2004
 */
public class RegexTextField extends JTextField {
	private String regex;
	private Color bg = valid;
	private static final Color valid = SystemColor.text;
	private static final Color invalid = new Color(255, 192, 192);
	private HashSet<FormElementListener> listeners = new HashSet<FormElementListener>();
	
	public void addFormElementListener(FormElementListener fel) {
		listeners.add(fel);
	}
	
	public void removeFormElementListener(FormElementListener fel) {
		listeners.remove(fel);
	}
	
	private void notifyFormElementListeners() {
		for (Iterator iter = listeners.iterator(); iter.hasNext();) {
			FormElementListener fel = (FormElementListener)iter.next();
			fel.inputChanged();
		}
	}
	
	public RegexTextField(String regex, String content) {
		super(content);
		init(regex);
	}
	
	public RegexTextField(String regex, String content, int length) {
		super(content, length);
		init(regex);
	}
	
	private void init(String regex) {
		this.regex = regex;
		setOpaque(false);
		addCaretListener(new CaretListener() {
			public void caretUpdate(CaretEvent e) {
				validateInput();
				notifyFormElementListeners();
			}
		});
		validateInput();
		
		addFocusListener(new FocusListener() {
			public void focusGained(FocusEvent e) {
				selectAll();
			}

			public void focusLost(FocusEvent e) {}
		});
	}

	private void validateInput() {
		String s = getText();
		if( (s != null) && s.matches(regex) ) {
			bg = valid;
		}
		else {
			bg = invalid;
		}
		repaint();
	}
	
	public void paintComponent(Graphics g) {
		g.setColor(bg);
		g.fillRect(0, 0, getWidth(), getHeight());
		
		super.paintComponent(g);
	}
	
	public boolean isInputValid() {
		return bg == valid;
	}
}
